package com.sugar.real.estate.module.business.config.convert;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ImageData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.IoUtils;
import com.alibaba.excel.util.ListUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

/**
 * @author Ysugar
 */
@Slf4j
public class UrlsStrImageConverter implements Converter<List<String>> {

    @Override
    public Class<?> supportJavaTypeKey() {
        return URL.class;
    }

    @Override
    public WriteCellData<?> convertToExcelData(List<String> values, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration)
            throws IOException {

        if (CollUtil.isEmpty(values))
            return new WriteCellData<>("");

        // 这里进行对数据实体类URL集合处理
        List<ImageData> data = ListUtils.newArrayList();
        ImageData imageData;
        // for 循环一次读取
        for (String imageUrl : values) {
            URL url = new URL(imageUrl);
            try (InputStream inputStream = url.openStream()) {
                byte[] bytes = IoUtils.toByteArray(inputStream);
                imageData = new ImageData();
                imageData.setImage(bytes);
                data.add(imageData);
            } catch (Exception e) {
                log.error("导出临时记录图片异常：", e);
            }
        }
        if (CollUtil.isEmpty(data))
            return new WriteCellData<>("");

        WriteCellData<?> cellData = new WriteCellData<>();
        // 图片返回图片列表
        cellData.setImageDataList(data);
        cellData.setType(CellDataTypeEnum.EMPTY);
        return cellData;
    }
}
